package demo3;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/class1")
public class class1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        // 初始化 count 值，仅在第一次访问时设置为 0
        if (servletContext.getAttribute("count") == null) {
            servletContext.setAttribute("count", 0);
        }
        incrementAndShowCount(servletContext, resp);
    }

    /**
     * 增加计数并显示结果
     * @param servletContext Servlet 上下文对象
     * @param resp 响应对象
     * @throws IOException 写入响应时可能抛出的异常
     */
    private void incrementAndShowCount(ServletContext servletContext, HttpServletResponse resp) throws IOException {
        int count = (int) servletContext.getAttribute("count");
        count++;
        servletContext.setAttribute("count", count);
        // 设置响应格式
        setResponseContentType(resp);
        resp.getWriter().println("容器中访问 servlet 的次数：" + count);
    }

    /**
     * 设置响应的内容类型和字符集
     * @param resp 响应对象
     */
    private void setResponseContentType(HttpServletResponse resp) {
        resp.setContentType("text/html; charset=UTF-8");
    }
}